import json
from selenium.common.exceptions import WebDriverException
from urllib.parse import urlparse
from view_geek_info import random_sleep_time


def chat_geek_info(driver):
    try:
        captured_urls = []

        # 每次页面加载后，启用 Network 并设置缓冲区
        driver.execute_cdp_cmd("Network.enable", {
            "maxTotalBufferSize": 10000000,
            "maxResourceBufferSize": 5000000
        })

        # 等待一段时间，确保页面加载并发起请求
        random_sleep_time()

        # 获取浏览器的性能日志
        logs = driver.get_log("performance")

        # 遍历日志，捕获相关网络请求和响应
        for item in logs:
            log = json.loads(item["message"])["message"]

            if log["method"] == 'Network.responseReceived':
                # 获取响应的URL
                urls = log['params']['response']['url']
                captured_urls.append(urls)

                # 定义目标 URL 的路径部分
                target_url_pattern = "https://www.zhipin.com/wapi/zpjob/chat/geek/info"

                try:
                    # 逐个处理 captured_urls 中的每个 URL
                    for captured_url in captured_urls:
                        # 解析 URL
                        parsed_url = urlparse(captured_url)
                        url_path = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"

                        # 检查 URL 路径是否匹配目标 URL
                        if url_path == target_url_pattern:
                            # print("是目标 URL 响应")
                            break
                except Exception as e:
                    print(f"发生错误: {e}")

                # 使用检查 URL 是否包含目标路径部分
                if target_url_pattern not in urls:
                    continue  # 如果匹配目标 URL，继续处理（或执行其他逻辑）

                # 打印请求的 URL
                # print('请求 URL:', urls)
                # 获取请求的ID
                request_id = log['params']['requestId']

                # 尝试获取请求的POST数据
                try:
                    request_data = driver.execute_cdp_cmd('Network.getRequestPostData',
                                                          {'requestId': request_id})
                    # print('请求数据:', request_data)
                except WebDriverException:  # 没有后台数据获取时会有异常
                    request_data = None

                # 获取响应的主体内容
                try:
                    response_body = driver.execute_cdp_cmd('Network.getResponseBody',
                                                           {'requestId': request_id}).get(
                        'body', None)
                    # print('响应体:', response_body)
                except WebDriverException as e:
                    print(f"获取响应失败: {e}")

                # 解析 JSON 数据
                data = json.loads(response_body)  # 将响应体解析为字典
                info_uid_data = data.get('zpData', {}).get('data', {})

                # 提取 job 数据字段
                if info_uid_data:
                    # 获取字段值
                    name = info_uid_data.get('name')
                    gender = info_uid_data.get('gender')
                    positionStatus = info_uid_data.get('positionStatus')
                    ageDesc = info_uid_data.get('ageDesc')
                    position = info_uid_data.get('position')
                    toPosition = info_uid_data.get('toPosition')
                    phone = info_uid_data.get('phone')
                    weixin = info_uid_data.get('weixin')

                    jobId = info_uid_data.get('jobId')
                    PositionName = info_uid_data.get('PositionName')
                    toPositionId = info_uid_data.get('toPositionId')
                    uid = info_uid_data.get('uid')

                    # 打印或处理提取的数据
                    # print(f"jobId: {jobId}")
                    # print(f"toPosition: {toPosition}")
                    # print(f"PositionName: {PositionName}")
                    # print(f"期望职位（岗位）: {toPositionId}")
                    print(f"手机号: {phone}")
                    print(f"微信: {weixin}")
                    # print(f"uid: {uid}")
                    print(f"姓名: {name}")
                    print(f"性别: {gender}")
                    print(f"求职状态（在职-离职）: {positionStatus}")
                    print(f"年龄: {ageDesc}")
                    print(f"职位名称: {position}")

                    # 将数据保存为 JSON 格式
                    with open('data/chat_geek.json', 'w', encoding='utf-8') as f:
                        json.dump(data, f, ensure_ascii=False, indent=4)
                        f.write('\n')

                else:
                    print("未找到有效的 job 数据")


    except Exception as e:
        print(f"发生错误: {e}")


def boss_msg_data(driver):
    try:
        captured_urls = []

        # # 每次页面加载后，启用 Network 并设置缓冲区
        # driver.execute_cdp_cmd("Network.enable", {
        #     "maxTotalBufferSize": 10000000,
        #     "maxResourceBufferSize": 5000000
        # })

        # 等待一段时间，确保页面加载并发起请求
        # random_sleep_time()

        # 获取浏览器的性能日志
        logs = driver.get_log("performance")

        # 遍历日志，捕获相关网络请求和响应
        for item in logs:
            log = json.loads(item["message"])["message"]

            if log["method"] == 'Network.responseReceived':
                # 获取响应的URL
                urls = log['params']['response']['url']
                captured_urls.append(urls)

                # 定义目标 URL 的路径部分
                target_url_pattern = "https://www.zhipin.com/wapi/zpchat/boss/historyMsg"

                try:
                    # 逐个处理 captured_urls 中的每个 URL
                    for captured_url in captured_urls:
                        # 解析 URL
                        parsed_url = urlparse(captured_url)
                        url_path = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"

                        # 检查 URL 路径是否匹配目标 URL
                        if url_path == target_url_pattern:
                            # print("是目标 URL 响应")
                            break
                except Exception as e:
                    print(f"发生错误: {e}")

                # 使用检查 URL 是否包含目标路径部分
                if target_url_pattern not in urls:
                    continue  # 如果匹配目标 URL，继续处理（或执行其他逻辑）

                # 打印请求的 URL
                print('请求 URL:', urls)
                # 获取请求的ID
                request_id = log['params']['requestId']

                # 尝试获取请求的POST数据
                try:
                    request_data = driver.execute_cdp_cmd('Network.getRequestPostData',
                                                          {'requestId': request_id})
                    print('请求数据:', request_data)
                except WebDriverException:  # 没有后台数据获取时会有异常
                    request_data = None

                # 获取响应的主体内容
                try:
                    response_body = driver.execute_cdp_cmd('Network.getResponseBody',
                                                           {'requestId': request_id}).get(
                        'body', None)
                    print('响应体:', response_body)
                except WebDriverException as e:
                    print(f"获取响应失败: {e}")

                # 解析 JSON 数据
                data = json.loads(response_body)  # 将响应体解析为字典
                zp_data = data.get('zpData', {})
                messages = zp_data.get('messages', [])

                # 遍历检查 pushText 内容
                for message in messages:
                    if isinstance(message, dict) and 'pushText' in message:
                        push_text = message['pushText']
                        if '请求与您交换微信' in push_text:
                            print(push_text)
                            return push_text

    except Exception as e:
        print(f"发生错误: {e}")